
import pymysql
# 使用 pymysql 连接 MySQL 数据库
db = pymysql.connect(
    host="localhost",  # 数据库地址
    user="root",  # 数据库用户名
    password="wxmp2014",  # 数据库密码
    database="fdds",  # 数据库名
    charset='utf8mb4',  # 解决中文字符问题
    cursorclass=pymysql.cursors.DictCursor  # 返回字典类型
)

cursor = db.cursor()

# 查询 books 表中的所有数据
cursor.execute("SELECT * FROM books LIMIT 1000")
books = cursor.fetchall()


# 字典来存储不同类别的书籍信息
categories = {}

for book in books:
    category = book['bookCategoryName']
    if category not in categories:
        categories[category] = []
    categories[category].append(book)

# 构建 HTML 内容字符串
html_content = ''
for category, books_in_category in categories.items():
    tab_id = category.replace(" ", "_")
    html_content += f'<div id="{tab_id}" class="content">\n'
    html_content += '<ul>\n'
    for book in books_in_category:
        title = book['title']
        video_url = book['videoUrl']
        html_content += f'    <li><a href="{video_url}">{title}</a></li>\n'
    html_content += '</ul>\n</div>\n'

# 构建 Tab 导航栏
tabs_html = '<div class="tabs">\n'
first_tab_id = None
for idx, (category, _) in enumerate(categories.items()):
    tab_id = category.replace(" ", "_")
    active_class = 'active' if idx == 0 else ''
    tabs_html += f'    <a href="#{tab_id}" class="tab-link {active_class}">{category}</a>\n'
    if idx == 0:
        first_tab_id = tab_id
tabs_html += '</div>\n'

# 确保第一个 Tab 默认激活
html_content = f'<div id="{first_tab_id}" class="content active">\n{html_content}'

# 最终的 container 内容
container_content = f'<div class="container">\n{tabs_html}{html_content}</div>'

print(container_content)

# 关闭数据库连接
cursor.close()
db.close()
